import { DesignPattern } from '@/types';

export const structuralPatterns: DesignPattern[] = [
  // 结构型模式 - 适配器
  {
    id: 'adapter',
    name: '适配器模式',
    category: 'structural',
    difficulty: '简单',
    description: '适配器模式允许接口不兼容的类一起工作。它充当两个不兼容接口之间的桥梁。',
    principles: [
      '将一个类的接口转换成客户希望的另一个接口',
      '使原本不兼容的类可以合作',
      '通过包装现有类来提供新接口',
      '不修改现有代码的情况下复用'
    ],
    useCases: [
      '第三方库集成',
      '遗留系统改造',
      'API接口统一',
      '数据格式转换',
      '插件系统'
    ],
    advantages: [
      '提高类的复用性',
      '增强系统的灵活性',
      '符合开闭原则',
      '分离接口和实现'
    ],
    disadvantages: [
      '增加系统复杂度',
      '可能影响性能',
      '过多适配器难以维护'
    ],
    code: `// 适配器模式示例
// 目标接口
interface MediaPlayer {
  play(audioType: string, fileName: string): void;
}

// 需要适配的接口
interface AdvancedMediaPlayer {
  playVlc(fileName: string): void;
  playMp4(fileName: string): void;
}

// 具体的高级播放器
class VlcPlayer implements AdvancedMediaPlayer {
  playVlc(fileName: string): void {
    console.log(\`Playing vlc file: \${fileName}\`);
  }
  
  playMp4(fileName: string): void {
    // 不支持mp4
  }
}

class Mp4Player implements AdvancedMediaPlayer {
  playVlc(fileName: string): void {
    // 不支持vlc
  }
  
  playMp4(fileName: string): void {
    console.log(\`Playing mp4 file: \${fileName}\`);
  }
}

// 适配器类
class MediaAdapter implements MediaPlayer {
  private advancedMusicPlayer: AdvancedMediaPlayer;
  
  constructor(audioType: string) {
    if (audioType === 'vlc') {
      this.advancedMusicPlayer = new VlcPlayer();
    } else if (audioType === 'mp4') {
      this.advancedMusicPlayer = new Mp4Player();
    }
  }
  
  play(audioType: string, fileName: string): void {
    if (audioType === 'vlc') {
      this.advancedMusicPlayer.playVlc(fileName);
    } else if (audioType === 'mp4') {
      this.advancedMusicPlayer.playMp4(fileName);
    }
  }
}

// 客户端类
class AudioPlayer implements MediaPlayer {
  private mediaAdapter: MediaAdapter;
  
  play(audioType: string, fileName: string): void {
    if (audioType === 'mp3') {
      console.log(\`Playing mp3 file: \${fileName}\`);
    } else if (audioType === 'vlc' || audioType === 'mp4') {
      this.mediaAdapter = new MediaAdapter(audioType);
      this.mediaAdapter.play(audioType, fileName);
    } else {
      console.log(\`\${audioType} format not supported\`);
    }
  }
}

// 使用示例
const player = new AudioPlayer();
player.play('mp3', 'song.mp3');
player.play('vlc', 'movie.vlc');
player.play('mp4', 'video.mp4');`,
    demoCode: `const player = new AudioPlayer();
player.play('mp3', 'song.mp3');
player.play('vlc', 'movie.vlc');
player.play('mp4', 'video.mp4');`,
    realWorldExamples: [
      {
        title: 'API接口适配',
        description: '统一不同API的调用方式',
        code: `class APIAdapter {
  constructor(private api: any) {}
  
  request(data: any) {
    return this.api.call(this.formatData(data));
  }
  
  private formatData(data: any) {
    // 转换数据格式
    return data;
  }
}`
      },
      {
        title: '数据库适配器',
        description: '统一不同数据库的操作接口',
        code: `class DatabaseAdapter {
  constructor(private db: any) {}
  
  find(query: any) {
    return this.db.select(this.convertQuery(query));
  }
}`
      }
    ],
    bestPractices: [
      '优先使用对象适配器而非类适配器',
      '保持适配器接口简洁',
      '考虑性能影响',
      '文档化适配逻辑'
    ],
    icon: 'Zap'
  },

  // 结构型模式 - 桥接
  {
    id: 'bridge',
    name: '桥接模式',
    category: 'structural',
    difficulty: '中等',
    description: '桥接模式将抽象部分与实现部分分离，使它们都可以独立地变化。',
    principles: [
      '分离抽象和实现',
      '通过组合建立联系',
      '支持独立扩展',
      '运行时切换实现'
    ],
    useCases: [
      '跨平台应用',
      '图形渲染系统',
      '数据库驱动',
      '消息发送系统',
      '设备驱动程序'
    ],
    advantages: [
      '分离接口和实现',
      '提高可扩展性',
      '实现细节对客户透明',
      '支持运行时切换'
    ],
    disadvantages: [
      '增加系统复杂度',
      '理解和设计难度较高',
      '可能过度设计'
    ],
    code: `// 桥接模式示例
// 实现接口
interface DrawingAPI {
  drawCircle(x: number, y: number, radius: number): void;
}

// 具体实现A
class DrawingAPI1 implements DrawingAPI {
  drawCircle(x: number, y: number, radius: number): void {
    console.log(\`API1.circle at \${x}:\${y} radius \${radius}\`);
  }
}

// 具体实现B
class DrawingAPI2 implements DrawingAPI {
  drawCircle(x: number, y: number, radius: number): void {
    console.log(\`API2.circle at \${x}:\${y} radius \${radius}\`);
  }
}

// 抽象类
abstract class Shape {
  protected drawingAPI: DrawingAPI;
  
  constructor(drawingAPI: DrawingAPI) {
    this.drawingAPI = drawingAPI;
  }
  
  abstract draw(): void;
  abstract resizeByPercentage(pct: number): void;
}

// 扩展抽象类
class CircleShape extends Shape {
  private x: number;
  private y: number;
  private radius: number;
  
  constructor(x: number, y: number, radius: number, drawingAPI: DrawingAPI) {
    super(drawingAPI);
    this.x = x;
    this.y = y;
    this.radius = radius;
  }
  
  draw(): void {
    this.drawingAPI.drawCircle(this.x, this.y, this.radius);
  }
  
  resizeByPercentage(pct: number): void {
    this.radius *= (1 + pct / 100);
  }
}

// 使用示例
const shapes = [
  new CircleShape(1, 2, 3, new DrawingAPI1()),
  new CircleShape(5, 7, 11, new DrawingAPI2())
];

shapes.forEach(shape => {
  shape.resizeByPercentage(2.5);
  shape.draw();
});`,
    demoCode: `const circle1 = new CircleShape(1, 2, 3, new DrawingAPI1());
const circle2 = new CircleShape(5, 7, 11, new DrawingAPI2());

circle1.draw();
circle2.draw();`,
    realWorldExamples: [
      {
        title: '跨平台UI',
        description: '抽象UI组件与平台实现分离',
        code: `abstract class Window {
  constructor(protected impl: WindowImpl) {}
  abstract draw(): void;
}

class WindowImpl {
  drawWindow() { /* 平台特定实现 */ }
}`
      },
      {
        title: '消息发送',
        description: '消息类型与发送方式分离',
        code: `abstract class Message {
  constructor(protected sender: MessageSender) {}
  abstract send(): void;
}

interface MessageSender {
  sendMessage(content: string): void;
}`
      }
    ],
    bestPractices: [
      '识别正交的变化维度',
      '保持抽象和实现的独立性',
      '使用组合而非继承',
      '考虑工厂模式创建桥接对象'
    ],
    icon: 'Network'
  },

  // 结构型模式 - 组合
  {
    id: 'composite',
    name: '组合模式',
    category: 'structural',
    difficulty: '中等',
    description: '组合模式将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。',
    principles: [
      '统一叶子和容器对象',
      '树形结构表示层次关系',
      '递归组合对象',
      '简化客户端代码'
    ],
    useCases: [
      '文件系统',
      'UI组件树',
      '组织架构',
      '菜单系统',
      '表达式解析'
    ],
    advantages: [
      '简化客户端代码',
      '容易增加新类型组件',
      '提供灵活的设计架构',
      '符合开闭原则'
    ],
    disadvantages: [
      '设计过于宽泛',
      '难以限制组件类型',
      '可能使设计变得复杂'
    ],
    code: `// 组合模式示例
// 组件接口
interface FileSystemComponent {
  getName(): string;
  getSize(): number;
  display(indent?: string): void;
}

// 叶子节点 - 文件
class File implements FileSystemComponent {
  private name: string;
  private size: number;
  
  constructor(name: string, size: number) {
    this.name = name;
    this.size = size;
  }
  
  getName(): string {
    return this.name;
  }
  
  getSize(): number {
    return this.size;
  }
  
  display(indent: string = ''): void {
    console.log(\`\${indent}📄 \${this.name} (\${this.size} bytes)\`);
  }
}

// 组合节点 - 文件夹
class Directory implements FileSystemComponent {
  private name: string;
  private children: FileSystemComponent[] = [];
  
  constructor(name: string) {
    this.name = name;
  }
  
  getName(): string {
    return this.name;
  }
  
  getSize(): number {
    return this.children.reduce((total, child) => total + child.getSize(), 0);
  }
  
  add(component: FileSystemComponent): void {
    this.children.push(component);
  }
  
  remove(component: FileSystemComponent): void {
    const index = this.children.indexOf(component);
    if (index > -1) {
      this.children.splice(index, 1);
    }
  }
  
  display(indent: string = ''): void {
    console.log(\`\${indent}📁 \${this.name}/ (\${this.getSize()} bytes total)\`);
    this.children.forEach(child => {
      child.display(indent + '  ');
    });
  }
}

// 使用示例
const root = new Directory('root');
const documents = new Directory('Documents');
const pictures = new Directory('Pictures');

const file1 = new File('resume.pdf', 1024);
const file2 = new File('photo1.jpg', 2048);
const file3 = new File('photo2.jpg', 1536);

documents.add(file1);
pictures.add(file2);
pictures.add(file3);

root.add(documents);
root.add(pictures);

root.display();`,
    demoCode: `const root = new Directory('root');
const docs = new Directory('Documents');
const file = new File('resume.pdf', 1024);

docs.add(file);
root.add(docs);
root.display();`,
    realWorldExamples: [
      {
        title: 'React组件树',
        description: '组件的嵌套结构',
        code: `interface Component {
  render(): string;
}

class Composite implements Component {
  private children: Component[] = [];
  
  add(component: Component) {
    this.children.push(component);
  }
  
  render(): string {
    return this.children.map(child => child.render()).join('');
  }
}`
      },
      {
        title: '菜单系统',
        description: '多级菜单结构',
        code: `class MenuItem {
  constructor(private name: string) {}
  
  click() {
    console.log(\`Clicked: \${this.name}\`);
  }
}

class Menu {
  private items: (MenuItem | Menu)[] = [];
  
  add(item: MenuItem | Menu) {
    this.items.push(item);
  }
}`
      }
    ],
    bestPractices: [
      '保持组件接口简单',
      '考虑使用访问者模式遍历',
      '注意内存管理和循环引用',
      '提供便捷的操作方法'
    ],
    icon: 'Layers'
  },

  // 结构型模式 - 装饰器
  {
    id: 'decorator',
    name: '装饰器模式',
    category: 'structural',
    difficulty: '中等',
    description: '装饰器模式允许向一个现有的对象添加新的功能，同时又不改变其结构。这种类型的设计模式属于结构型模式，它是作为现有的类的一个包装。',
    principles: [
      '动态地给对象添加功能',
      '比继承更灵活的扩展方式',
      '保持接口一致性',
      '支持多层装饰'
    ],
    useCases: [
      'UI组件增强',
      '数据流处理',
      '缓存系统',
      '日志记录',
      '权限控制'
    ],
    advantages: [
      '比继承更灵活',
      '可以动态添加功能',
      '符合开闭原则',
      '可以组合多个装饰器'
    ],
    disadvantages: [
      '增加代码复杂度',
      '装饰器过多时难以理解',
      '可能产生很多小对象'
    ],
    code: `// 装饰器模式示例
// 组件接口
interface Coffee {
  cost(): number;
  description(): string;
}

// 具体组件
class SimpleCoffee implements Coffee {
  cost(): number {
    return 10;
  }
  
  description(): string {
    return 'Simple coffee';
  }
}

// 装饰器基类
abstract class CoffeeDecorator implements Coffee {
  protected coffee: Coffee;
  
  constructor(coffee: Coffee) {
    this.coffee = coffee;
  }
  
  cost(): number {
    return this.coffee.cost();
  }
  
  description(): string {
    return this.coffee.description();
  }
}

// 具体装饰器
class MilkDecorator extends CoffeeDecorator {
  constructor(coffee: Coffee) {
    super(coffee);
  }
  
  cost(): number {
    return this.coffee.cost() + 2;
  }
  
  description(): string {
    return this.coffee.description() + ', milk';
  }
}

class SugarDecorator extends CoffeeDecorator {
  constructor(coffee: Coffee) {
    super(coffee);
  }
  
  cost(): number {
    return this.coffee.cost() + 1;
  }
  
  description(): string {
    return this.coffee.description() + ', sugar';
  }
}

class WhipDecorator extends CoffeeDecorator {
  constructor(coffee: Coffee) {
    super(coffee);
  }
  
  cost(): number {
    return this.coffee.cost() + 3;
  }
  
  description(): string {
    return this.coffee.description() + ', whip';
  }
}

// 使用示例
let coffee: Coffee = new SimpleCoffee();
console.log(\`\${coffee.description()} costs \${coffee.cost()}\`);

coffee = new MilkDecorator(coffee);
console.log(\`\${coffee.description()} costs \${coffee.cost()}\`);

coffee = new SugarDecorator(coffee);
console.log(\`\${coffee.description()} costs \${coffee.cost()}\`);

coffee = new WhipDecorator(coffee);
console.log(\`\${coffee.description()} costs \${coffee.cost()}\`);`,
    demoCode: `let coffee: Coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
console.log(\`\${coffee.description()} costs \${coffee.cost()}\`);`,
    realWorldExamples: [
      {
        title: 'React高阶组件',
        description: '为组件添加额外功能',
        code: `function withLoading<T>(Component: React.ComponentType<T>) {
  return (props: T & { loading: boolean }) => {
    if (props.loading) return <div>Loading...</div>;
    return <Component {...props} />;
  };
}`
      },
      {
        title: '中间件模式',
        description: '为请求添加处理层',
        code: `class RequestDecorator {
  constructor(private request: Request) {}
  
  withAuth(token: string) {
    this.request.headers.set('Authorization', \`Bearer \${token}\`);
    return this;
  }
  
  withLogging() {
    console.log('Request:', this.request.url);
    return this;
  }
}`
      }
    ],
    bestPractices: [
      '保持装饰器接口一致',
      '避免过度装饰',
      '考虑装饰器的顺序',
      '提供便捷的组合方法'
    ],
    icon: 'Sparkles'
  },

  // 结构型模式 - 外观
  {
    id: 'facade',
    name: '外观模式',
    category: 'structural',
    difficulty: '简单',
    description: '外观模式为子系统中的一组接口提供一个一致的界面，外观模式定义了一个高层接口，这个接口使得这一子系统更加容易使用。',
    principles: [
      '提供统一的高层接口',
      '隐藏子系统的复杂性',
      '降低客户端与子系统的耦合',
      '简化客户端调用'
    ],
    useCases: [
      'API网关',
      '第三方库封装',
      '复杂系统简化',
      '遗留系统集成',
      '微服务聚合'
    ],
    advantages: [
      '简化客户端接口',
      '降低系统耦合度',
      '提高安全性',
      '便于维护和扩展'
    ],
    disadvantages: [
      '可能成为性能瓶颈',
      '增加一层抽象',
      '可能违反开闭原则'
    ],
    code: `// 外观模式示例
// 子系统类
class CPU {
  freeze(): void {
    console.log('CPU: Freezing processor');
  }
  
  jump(position: number): void {
    console.log(\`CPU: Jumping to position \${position}\`);
  }
  
  execute(): void {
    console.log('CPU: Executing instructions');
  }
}

class Memory {
  load(position: number, data: string): void {
    console.log(\`Memory: Loading data "\${data}" at position \${position}\`);
  }
}

class HardDrive {
  read(lba: number, size: number): string {
    console.log(\`HardDrive: Reading \${size} bytes from LBA \${lba}\`);
    return 'boot data';
  }
}

// 外观类
class ComputerFacade {
  private cpu: CPU;
  private memory: Memory;
  private hardDrive: HardDrive;
  
  constructor() {
    this.cpu = new CPU();
    this.memory = new Memory();
    this.hardDrive = new HardDrive();
  }
  
  start(): void {
    console.log('ComputerFacade: Starting computer...');
    this.cpu.freeze();
    const bootData = this.hardDrive.read(0, 1024);
    this.memory.load(0, bootData);
    this.cpu.jump(0);
    this.cpu.execute();
    console.log('ComputerFacade: Computer started successfully!');
  }
}

// 使用示例
const computer = new ComputerFacade();
computer.start();`,
    demoCode: `const computer = new ComputerFacade();
computer.start();`,
    realWorldExamples: [
      {
        title: 'API网关',
        description: '统一多个微服务的访问接口',
        code: `class APIGateway {
  constructor(
    private userService: UserService,
    private orderService: OrderService,
    private paymentService: PaymentService
  ) {}
  
  async getUserProfile(userId: string) {
    const user = await this.userService.getUser(userId);
    const orders = await this.orderService.getUserOrders(userId);
    const payments = await this.paymentService.getUserPayments(userId);
    
    return { user, orders, payments };
  }
}`
      },
      {
        title: '数据库操作封装',
        description: '简化复杂的数据库操作',
        code: `class DatabaseFacade {
  async saveUser(userData: any) {
    await this.validateUser(userData);
    await this.hashPassword(userData);
    await this.insertUser(userData);
    await this.sendWelcomeEmail(userData);
  }
  
  private async validateUser(data: any) { /* ... */ }
  private async hashPassword(data: any) { /* ... */ }
  private async insertUser(data: any) { /* ... */ }
  private async sendWelcomeEmail(data: any) { /* ... */ }
}`
      }
    ],
    bestPractices: [
      '保持外观接口简洁',
      '不要暴露子系统细节',
      '考虑性能影响',
      '提供合理的抽象层次'
    ],
    icon: 'Shield'
  },

  // 结构型模式 - 享元
  {
    id: 'flyweight',
    name: '享元模式',
    category: 'structural',
    difficulty: '困难',
    description: '享元模式通过共享技术来有效地支持大量细粒度对象的复用。它通过共享已存在的对象来大幅度减少需要创建的对象数量、避免大量相似类的开销。',
    principles: [
      '分离内部状态和外部状态',
      '共享相同的内部状态',
      '外部状态由客户端维护',
      '减少对象创建数量'
    ],
    useCases: [
      '文本编辑器字符渲染',
      '游戏中的粒子系统',
      '图形界面组件',
      '缓存系统',
      '数据库连接池'
    ],
    advantages: [
      '大幅减少内存使用',
      '提高程序性能',
      '集中管理共享对象',
      '支持大量对象'
    ],
    disadvantages: [
      '增加程序复杂度',
      '需要分离内外部状态',
      '可能引入线程安全问题'
    ],
    code: `// 享元模式示例
// 享元接口
interface TreeType {
  render(canvas: string, x: number, y: number): void;
}

// 具体享元类
class TreeTypeFlyweight implements TreeType {
  private name: string;
  private color: string;
  private sprite: string;
  
  constructor(name: string, color: string, sprite: string) {
    this.name = name;
    this.color = color;
    this.sprite = sprite;
  }
  
  render(canvas: string, x: number, y: number): void {
    console.log(\`Rendering \${this.name} tree (\${this.color}) at (\${x}, \${y}) on \${canvas}\`);
  }
}

// 享元工厂
class TreeTypeFactory {
  private static treeTypes: Map<string, TreeType> = new Map();
  
  static getTreeType(name: string, color: string, sprite: string): TreeType {
    const key = \`\${name}-\${color}-\${sprite}\`;
    
    if (!this.treeTypes.has(key)) {
      console.log(\`Creating new TreeType: \${key}\`);
      this.treeTypes.set(key, new TreeTypeFlyweight(name, color, sprite));
    } else {
      console.log(\`Reusing existing TreeType: \${key}\`);
    }
    
    return this.treeTypes.get(key)!;
  }
  
  static getCreatedTreeTypesCount(): number {
    return this.treeTypes.size;
  }
}

// 上下文类（包含外部状态）
class Tree {
  private x: number;
  private y: number;
  private type: TreeType;
  
  constructor(x: number, y: number, type: TreeType) {
    this.x = x;
    this.y = y;
    this.type = type;
  }
  
  render(canvas: string): void {
    this.type.render(canvas, this.x, this.y);
  }
}

// 森林类（客户端）
class Forest {
  private trees: Tree[] = [];
  
  plantTree(x: number, y: number, name: string, color: string, sprite: string): void {
    const type = TreeTypeFactory.getTreeType(name, color, sprite);
    const tree = new Tree(x, y, type);
    this.trees.push(tree);
  }
  
  render(canvas: string): void {
    this.trees.forEach(tree => tree.render(canvas));
  }
  
  getTreeCount(): number {
    return this.trees.length;
  }
}

// 使用示例
const forest = new Forest();

// 种植大量树木
for (let i = 0; i < 1000; i++) {
  forest.plantTree(
    Math.random() * 100,
    Math.random() * 100,
    Math.random() > 0.5 ? 'Oak' : 'Pine',
    Math.random() > 0.5 ? 'Green' : 'Brown',
    'tree.png'
  );
}

console.log(\`Total trees: \${forest.getTreeCount()}\`);
console.log(\`Tree types created: \${TreeTypeFactory.getCreatedTreeTypesCount()}\`);

forest.render('Canvas');`,
    demoCode: `const forest = new Forest();
forest.plantTree(10, 20, 'Oak', 'Green', 'tree.png');
forest.plantTree(30, 40, 'Oak', 'Green', 'tree.png'); // 复用享元
console.log(\`Tree types: \${TreeTypeFactory.getCreatedTreeTypesCount()}\`);`,
    realWorldExamples: [
      {
        title: '文本编辑器',
        description: '字符对象的享元实现',
        code: `class CharacterFlyweight {
  constructor(private char: string, private font: string) {}
  
  render(x: number, y: number, color: string) {
    console.log(\`Render '\${this.char}' at (\${x},\${y}) in \${color}\`);
  }
}

class CharacterFactory {
  private static characters = new Map<string, CharacterFlyweight>();
  
  static getCharacter(char: string, font: string): CharacterFlyweight {
    const key = \`\${char}-\${font}\`;
    if (!this.characters.has(key)) {
      this.characters.set(key, new CharacterFlyweight(char, font));
    }
    return this.characters.get(key)!;
  }
}`
      },
      {
        title: '游戏粒子系统',
        description: '粒子效果的享元优化',
        code: `class ParticleType {
  constructor(private sprite: string, private color: string) {}
  
  render(x: number, y: number, velocity: number) {
    // 渲染粒子
  }
}

class Particle {
  constructor(
    private x: number,
    private y: number,
    private velocity: number,
    private type: ParticleType
  ) {}
}`
      }
    ],
    bestPractices: [
      '仔细分析内外部状态',
      '确保享元对象不可变',
      '使用工厂管理享元对象',
      '考虑线程安全问题'
    ],
    icon: 'Zap'
  },

  // 结构型模式 - 代理
  {
    id: 'proxy',
    name: '代理模式',
    category: 'structural',
    difficulty: '中等',
    description: '代理模式为另一个对象提供一个替身或占位符以控制对这个对象的访问。代理控制着对于原对象的访问，并允许在将请求提交给对象前后进行一些处理。',
    principles: [
      '为其他对象提供代理以控制访问',
      '在客户端和目标对象之间起到中介作用',
      '可以在不改变目标对象的情况下扩展功能',
      '支持延迟初始化和访问控制'
    ],
    useCases: [
      '虚拟代理（延迟加载）',
      '保护代理（访问控制）',
      '缓存代理（结果缓存）',
      '远程代理（网络访问）',
      '智能引用代理'
    ],
    advantages: [
      '控制对象访问',
      '可以延迟对象创建',
      '实现访问控制',
      '可以缓存结果'
    ],
    disadvantages: [
      '增加系统复杂度',
      '可能影响性能',
      '增加响应时间'
    ],
    code: `// 代理模式示例
// 主题接口
interface Image {
  display(): void;
}

// 真实主题
class RealImage implements Image {
  private filename: string;
  
  constructor(filename: string) {
    this.filename = filename;
    this.loadFromDisk();
  }
  
  private loadFromDisk(): void {
    console.log(\`Loading image: \${this.filename}\`);
    // 模拟耗时的加载过程
    for (let i = 0; i < 1000000000; i++) {
      // 模拟加载时间
    }
    console.log(\`Image loaded: \${this.filename}\`);
  }
  
  display(): void {
    console.log(\`Displaying image: \${this.filename}\`);
  }
}

// 代理类
class ProxyImage implements Image {
  private realImage: RealImage | null = null;
  private filename: string;
  
  constructor(filename: string) {
    this.filename = filename;
  }
  
  display(): void {
    if (this.realImage === null) {
      console.log('ProxyImage: Creating real image...');
      this.realImage = new RealImage(this.filename);
    }
    this.realImage.display();
  }
}

// 缓存代理示例
class CacheProxy implements Image {
  private realImage: RealImage | null = null;
  private filename: string;
  private static cache: Map<string, RealImage> = new Map();
  
  constructor(filename: string) {
    this.filename = filename;
  }
  
  display(): void {
    if (CacheProxy.cache.has(this.filename)) {
      console.log('CacheProxy: Using cached image');
      this.realImage = CacheProxy.cache.get(this.filename)!;
    } else {
      console.log('CacheProxy: Creating and caching image');
      this.realImage = new RealImage(this.filename);
      CacheProxy.cache.set(this.filename, this.realImage);
    }
    this.realImage.display();
  }
}

// 保护代理示例
class ProtectionProxy implements Image {
  private realImage: RealImage;
  private userRole: string;
  
  constructor(filename: string, userRole: string) {
    this.realImage = new RealImage(filename);
    this.userRole = userRole;
  }
  
  display(): void {
    if (this.userRole === 'admin' || this.userRole === 'user') {
      this.realImage.display();
    } else {
      console.log('ProtectionProxy: Access denied. Insufficient permissions.');
    }
  }
}

// 使用示例
console.log('=== Virtual Proxy ===');
const image1 = new ProxyImage('photo1.jpg');
console.log('Image created, but not loaded yet');
image1.display(); // 此时才真正加载
image1.display(); // 直接显示，不再加载

console.log('\\n=== Cache Proxy ===');
const image2 = new CacheProxy('photo2.jpg');
const image3 = new CacheProxy('photo2.jpg'); // 相同文件名
image2.display();
image3.display(); // 使用缓存

console.log('\\n=== Protection Proxy ===');
const adminImage = new ProtectionProxy('secret.jpg', 'admin');
const guestImage = new ProtectionProxy('secret.jpg', 'guest');
adminImage.display(); // 允许访问
guestImage.display(); // 拒绝访问`,
    demoCode: `const image = new ProxyImage('photo.jpg');
console.log('Image proxy created');
image.display(); // 延迟加载
image.display(); // 直接显示`,
    realWorldExamples: [
      {
        title: 'HTTP请求代理',
        description: '为HTTP请求添加缓存和重试机制',
        code: `class HTTPProxy {
  private cache = new Map<string, any>();
  
  async get(url: string) {
    if (this.cache.has(url)) {
      return this.cache.get(url);
    }
    
    const response = await fetch(url);
    const data = await response.json();
    this.cache.set(url, data);
    return data;
  }
}`
      },
      {
        title: '数据库连接代理',
        description: '控制数据库访问和连接池管理',
        code: `class DatabaseProxy {
  constructor(private user: User) {}
  
  query(sql: string) {
    if (!this.user.hasPermission('read')) {
      throw new Error('Access denied');
    }
    
    return this.database.execute(sql);
  }
}`
      }
    ],
    bestPractices: [
      '保持代理接口与真实对象一致',
      '合理使用不同类型的代理',
      '注意代理链的性能影响',
      '考虑线程安全问题'
    ],
    icon: 'Shield'
  }
];
